const fs = require('fs')

const cors = require('cors')
const jwt = require('jsonwebtoken')
const bodyParser = require('body-parser')

module.exports = {
    devServer: {
        before(app, serve) {
            app.use(cors())
            app.use(bodyParser.json())
            app.use(bodyParser.urlencoded({ extended: false }))

            app.post('/api/login',(req, res) => {
                const user = req.body.id
                res.json({
                    token: jwt.sign({ user: user }, 'abcd', {
                        // 过期时间
                        expiresIn: '3000s'
                    }),
                    user,
                    state: 1,
                    file: '/image/job/Tezhong.jpg',
                    code: 200,
                    id: 62
                })
            })

            app.post('/api/validate', function (req, res) {
                const token = req.headers.authorization
                // 验证token合法性，对token进行解码
                jwt.verify(token, 'abcd', function (err, decode) {
                    if (err) {
                        res.json({
                            msg: '当前用户未登录'
                        })
                    } else {
                        // 证明用户已经登录
                        res.json({
                            token: jwt.sign({ user: decode.user }, 'abcd', {
                                expiresIn: '3000s'
                            }),
                            user: decode.user,
                            msg: '已登录',
                            state: 1,
                            file: '/image/job/Tezhong.jpg',
                            code: 200,
                            id: 62
                        })
                    }
                })
            })
        }
    }
}